package com.ibeetl.member.web;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.conf.PasswordConfig;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.*;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.member.entity.Member;
import com.ibeetl.member.rbac.MemberLoginInfo;
import com.ibeetl.member.service.MemberService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

/**
 * 会员管理接口
 * 
 * @author xiandafu
 */
@Controller
public class MemberController {
	private final Log log = LogFactory.getLog(this.getClass());
	private static final String MODEL = "/core/member";

	@Autowired
	PasswordConfig.PasswordEncryptService passwordEncryptService;

	@Autowired
	MemberService memberService;

	@Autowired
	CorePlatformService platformService;

	@Autowired
	FileService fileService;

	@Autowired
	HttpRequestLocal httpRequestLocal;

	@Autowired
	Environment env;

	@PostMapping(MODEL + "/loginNameVerify.json")
	@ResponseBody
	public JsonResult loginNameVerify(@RequestParam(required = true) String loginName) {
		//TODO 点击登录弹出框第一次不居中问题
		Member member = memberService.getMemberByLoginName(loginName);
		Member currentMember = platformService.getCurrentMemberOnly();
		if (member != null) {
			if (currentMember != null && member.getId().intValue() != currentMember.getId().intValue()) {
				return JsonResult.failMessage("用户名已被占用");
			} else {
				return JsonResult.successMessage("用户名可以使用");
			}
		} else {
			return JsonResult.successMessage("用户名可以使用");
		}
	}

	@PostMapping(MODEL + "/domainVerify.json")
	@ResponseBody
	public JsonResult domainVerify(@RequestParam(required = true) String domain) {
		Member member = memberService.getMemberByDomain(domain);
		Member currentMember = platformService.getCurrentMemberOnly();
		if (member != null) {
			if (currentMember != null && member.getId().intValue() != currentMember.getId().intValue()) {
				return JsonResult.failMessage("域名已被占用");
			}else {
				return JsonResult.successMessage("域名可以使用");
			}
		} else {
			return JsonResult.successMessage("域名可以使用");
		}
	}


	@GetMapping(MODEL + "/edit.do")
	@Function("member.edit")
	public ModelAndView edit(String id) {
		ModelAndView view = new ModelAndView("/admin/user/edit.html");
		Member user = memberService.queryById(id);
		view.addObject("user", user);
		return view;
	}

	@GetMapping(MODEL + "/add.do")
	@Function("member.add")
	public ModelAndView add() {
		ModelAndView view = new ModelAndView("/admin/user/add.html");
		return view;
	}

	@GetMapping(MODEL + "/changePassword.do")
	@Function("member")
	public ModelAndView changePassword(Long id) {
		Member user = memberService.queryById(id);
		ModelAndView view = new ModelAndView("/admin/user/changePassword.html");
		view.addObject("user", user);
		return view;
	}


	@PostMapping(MODEL + "/logout.json")
	@ResponseBody
	public JsonResult logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		this.platformService.removeLoginMember();
		return JsonResult.successMessage("会员退出登录成功");
	}

	@PostMapping(MODEL + "/update.json")
	@ResponseBody
	public JsonResult update(@Validated({ValidateConfig.UPDATE.class})  Member member, HttpServletRequest request) {
		member = this.memberService.queryById(member.getId());
		member = ParamUtil.initParameterObj(request, member);
		String[] type2Array = request.getParameterValues("type2Value[]");
		String type2Str = StringUtils.join(type2Array,",");
		member.setType2(type2Str);
		int success = memberService.upsert(member);
		if (success > 0) {
			this.platformService.clearFunctionCache();
			return JsonResult.success();
		} else {
			return JsonResult.failMessage("保存失败！");
		}
	}

	@PostMapping(MODEL + "/reg.json")
	@ResponseBody
	public JsonResult<Integer> add(@Validated(ValidateConfig.ADD.class) Member member, HttpServletRequest request) throws IOException {
		if (member != null && member.getId() != null) {
			return this.update(member,request);
		}
		member.setCreateTime(new Date());
		member.setPassword(passwordEncryptService.password(member.getPassword()));

		String photo = request.getParameter("photo");
		if (StringUtils.isBlank(photo)) {
			member.setPhoto(String.valueOf(getPhotoFileId()));
		}

		String[] type2Array = request.getParameterValues("type2Value[]");
		String type2Str = StringUtils.join(type2Array,",");
		member.setType2(type2Str);

		memberService.upsert(member);
		return JsonResult.success(member.getId());
	}
	public Long getPhotoFileId() {
		// 随机分配头像
		String faceWebDir = FileItem.getRoot(env) + File.separator + "face";
		File faceDir = new File(faceWebDir);

		File[] faceFiles = faceDir.listFiles();
		int faceCount = faceFiles.length;
		Random random = new Random();
		int count = random.nextInt(faceCount);
		File faceFile = faceFiles[count];
		String faceFileName = faceFile.getName();

		String path = File.separator + "face" + File.separator + faceFileName;
		String uuid = UUIDUtil.uuid();
		FileItem fileItem = fileService.createFileItem(faceFile.getName(), "头像", path, uuid);

		return fileItem.getId();
	}
	public void initMember(Member member) {

	}

	@PostMapping(MODEL + "/login.json")
	@ResponseBody
	public JsonResult<MemberLoginInfo> login(String loginName, String password) {
		if (StringUtils.isBlank(loginName) || StringUtils.isBlank(password)) {
			throw new PlatformException("用户名密码不能为空");
		}
		MemberLoginInfo info = memberService.login(loginName, password);
		Member member = info.getMember();
		// 记录登录信息到session
		this.platformService.setLoginMember(info.getMember());
		return JsonResult.success(info);
	}

	@PostMapping(MODEL + "/view.json")
	@ResponseBody
	@Function("member")
	public JsonResult<Member> view(Long id) {
		Member user = memberService.queryById(id);
		return JsonResult.success(user);
	}



	/**
	 * 管理员重置用户密码
	 *
	 * @return
	 */
	@PostMapping(MODEL + "/changePassword.json")
	@Function("member.password")
	@ResponseBody
	public JsonResult changePassword(Integer id, String password) {

		memberService.resetPassword(id, password);
		return new JsonResult().success();
	}


}
